package com.kehutong.message.urlConfig;

import java.util.List;
import org.coraframework.boot.Application;
import org.coraframework.config.Config;
import org.coraframework.http.HttpClient;
import org.coraframework.inject.Singleton;
import org.coraframework.json.JSON;
import org.coraframework.json.JSONObject;
import org.coraframework.util.CallBack;
import org.coraframework.util.Objects;
import com.kehutong.common.AccessTokenExpiredException;
import com.kehutong.common.errcode.ErrorCode;
import com.kehutong.common.urlconfig.UrlConfig;

/**
 * 企业微信相关url配置
 */
@Singleton
public class WorkerUrlConfig extends UrlConfig {
    protected WorkerUrlConfig() {
        super("tencent", "work_url");
    }

    private int index;;
    private List<String> urlList;

    @Override
    public String getUrl() {
        return url;
    }

    /**
     * 固定IP获取数据，主要用于登陆
     * @param page
     * @param client
     * @return
     * @throws Exception
     */
    public JSONObject postFixed(String page, CallBack<HttpClient> client) throws Exception {
        final HttpClient httpClient = HttpClient.create(url + page);
        client.call(httpClient);

        String text = httpClient.post();
        final JSONObject rs = JSON.parseObject(text);

        ErrorCode errCode = ErrorCode.of(rs, "errcode");
        if (errCode == ErrorCode.WORK_OK) {
            return rs;
        } else if (errCode == ErrorCode.WORK_42001) {
            throw new AccessTokenExpiredException(rs.getString("errmsg"));
        } else if (errCode == ErrorCode.WORK_81013) {
            // 员工无权限
            return null;
        }  else {
            logger.error("{}: [errCode:{}, errMsg: {}", page, rs.getIntValue("errcode"), rs.getString("errmsg"));
            throw new RuntimeException(errCode.message);
        }
    }

    protected ErrorCode getErrorCode(String page, JSONObject rs, CallBack<JSONObject> dataCallBack) throws Exception{
        ErrorCode errCode = ErrorCode.of(rs, "errcode");
        if (errCode == ErrorCode.WORK_OK) {
            if (Objects.nonNull(dataCallBack)) {
                dataCallBack.call(rs);
            }
        } else if (errCode == ErrorCode.WORK_42001) {
            throw new AccessTokenExpiredException(rs.getString("errmsg"));
        } else {
            logger.error("{}: [errCode:{}, errMsg: {}", page, rs.getIntValue("errcode"), rs.getString("errmsg"));
        }

        return errCode;
    }


    /**
     * post请求,返回json
     * @param page
     * @param client
     * @return
     * @throws Exception
     */
    public JSONObject post(String page, CallBack<HttpClient> client) throws Exception {
        final HttpClient httpClient = HttpClient.create(getUrl() + page);
        client.call(httpClient);

        String text = httpClient.post();
        if (httpClient.getResponseCode() != 200) {
            return httpError(httpClient.getResponseCode(), "http状态错误");
        }

        return JSON.parseObject(text);
    }
}
